/**
 * Created by oneminute on 14-5-25.
 */

var lz = require("../utils/modules")();

function Email(_opts) {
    lz.Persistent.call(this, _opts);
    if (!_opts) _opts = {};
    this.__properties.pushArray([
        { name: "email", value: _opts.email || "" },
        { name: "uid", value: _opts.uid || "" },
        { name: "authenticated", value: false },
        { name: "authtime", value: null },
        { name: "authcode", value: null }
    ]);
    this.__initProperties();
    this.__collection = lz.Config.db.arango.emails;
    this.__aql = lz.Config.db.arango.aqls.GET_OBJECT_BY_PROPERTY;
}

require("util").inherits(Email, lz.Persistent);

Email.prototype.__init = function (_email) {
    this.email = "";
    this.uid = "";
    this.authenticated = false;
    this.authtime = null;
    this.authcode = null;

    if (_email) {
        for (var p in this) {
            if (_email[p] != undefined)
                this[p] = _email[p];
        }
    }
};

Email.prototype.validate = function () {
    return exports.validate(this);
};

exports.validate = function (_email) {
    var errors = [];
    var result = {};

    if (_email.hasOwnProperty('email')) {
        if (!config.regexps.email.test(_email.email)) {
            errors.push({name: 'email', error: config.errors.VALIDATE_INVALIDATE_VALUE});
        }
    } else {
        errors.push({name: 'email', error: config.errors.VALIDATE_PROPERTY_NOT_FOUND});
    }

    if (_email.hasOwnProperty('uid')) {
        if (_email.uid.length != 34 || typeof _email.uid != 'string') {
            errors.push({name: 'uid', error: config.errors.VALIDATE_INVALIDATE_VALUE});
        }
    } else {
        errors.push({name: 'uid', error: config.errors.VALIDATE_PROPERTY_NOT_FOUND});
    }

    if (_email.hasOwnProperty('authenticated')) {
        if (typeof _email.authenticated != 'boolean') {
            errors.push({name: 'authenticated', error: config.errors.VALIDATE_INVALIDATE_VALUE});
        }
    } else {
        errors.push({name: 'authenticated', error: config.errors.VALIDATE_PROPERTY_NOT_FOUND});
    }

    if (_email.hasOwnProperty('authtime')) {
        if (_email.authenticated) {
            if (!config.regexps.datetime_short.test(_email.authtime)) {
                errors.push({name: 'authtime', error: config.errors.VALIDATE_INVALIDATE_VALUE});
            }
        }
    } else {
        errors.push({name: 'authtime', error: config.errors.VALIDATE_PROPERTY_NOT_FOUND});
    }

    if (_email.hasOwnProperty('authcode')) {

    } else {
        errors.push({name: 'authcode', error: config.errors.VALIDATE_PROPERTY_NOT_FOUND});
    }

    if (errors.length == 0) {
        result.result = true;
    } else {
        result.result = false;
        result.errors = errors;
    }

    return result;
};

exports = module.exports = Email;
